package com.lw.lost.adapters

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.lw.lost.databinding.ItemManagePostBinding
import com.lw.lost.models.Post

class ManagePostAdapter(
    private val onPostClick: (Post) -> Unit,
    private val onActionClick: (Post) -> Unit
) : ListAdapter<Post, ManagePostAdapter.ViewHolder>(DiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            ItemManagePostBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
        )
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    inner class ViewHolder(
        private val binding: ItemManagePostBinding
    ) : RecyclerView.ViewHolder(binding.root) {

        fun bind(post: Post) {
            binding.apply {
                tvContent.text = post.content
                tvTime.text = post.createTime
                tvStatus.text = if (post.status == 0) "正常" else "已删除"
                
                btnAction.isEnabled = post.status == 0
                btnAction.text = if (post.status == 0) "删除" else "已删除"
                btnAction.setOnClickListener { onActionClick(post) }

                root.setOnClickListener { onPostClick(post) }
            }
        }
    }

    private class DiffCallback : DiffUtil.ItemCallback<Post>() {
        override fun areItemsTheSame(oldItem: Post, newItem: Post) =
            oldItem.postId == newItem.postId

        override fun areContentsTheSame(oldItem: Post, newItem: Post) =
            oldItem == newItem
    }
} 